import { ref, onUnmounted, reactive } from 'vue';  
  
// 倒计时组合式API函数  
export function useCountdown() {  
  // 响应式状态  
  const state = reactive({  
    countdown: 60, // 剩余时间  
    isCounting: false, // 是否正在倒计时  
    canSendAgain: false, // 是否可以重新发送验证码  
  });  
  
  // 定时器引用  
  let timer = null;  
  
  // 开始倒计时  
  function startCountdown() {  
    if (state.isCounting || state.countdown <= 0) return;  
  
    state.isCounting = true;  
    state.canSendAgain = false;  
  
    timer = setInterval(() => {  
      if (state.countdown > 0) {  
        state.countdown--;  
      } else {  
        // 倒计时结束  
        clearInterval(timer);  
        timer = null;  
        state.isCounting = false;  
        state.canSendAgain = true; // 允许重新发送验证码  
      }  
    }, 1000);  
  }  
  
  // 停止倒计时  
  function stopCountdown() {  
    if (timer) {  
      clearInterval(timer);  
      timer = null;  
      state.isCounting = false;  
    }  
  }  
  
  // 重置倒计时  
  function resetCountdown() {  
    stopCountdown();  
    state.countdown = 60;  
    state.canSendAgain = false;  
	startCountdown();
  }  
  
  // 组件卸载时清除定时器  
  onUnmounted(() => {  
    stopCountdown();  
  });  
  
  // 公开的方法  
  return {  
    state,  
    startCountdown,  
    stopCountdown,  
    resetCountdown,  
  };  
}  
  
